package com.serv.common.model.sys;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.Model;

@SuppressWarnings("serial")
public class Organization extends Model<Organization> {
	public static Organization dao = new Organization().dao();
	
	public List<Role> roles() {
		String sql = "select R.* from sys_organization_role OR left join sys_role R on OR.role_id=R.id where OR.organization_id=?";
		return Role.dao.find(sql,get("id"));
	}
	
	public List<Organization> flatDescendant(){
		String id = getStr("id");
		return dao.find("select * from sys_organization where id like ?",id+"%");
	}
	
	public Organization treeDescendant() {
		List<Organization> descendant = flatDescendant();
		makeTree(this,descendant);
		return this;
	}
	
	private void makeTree(Organization parent, List<Organization> list) {
		List<Organization> children = new ArrayList<Organization>();
		
		String pId = parent.getStr("id");
		for(Organization item: list) {
			String childId = item.getStr("id");
			boolean isSon = childId.startsWith(pId)&&childId.length()==pId.length()+3;
			if(isSon) {
				makeTree(item,list);
				children.add(item);
			}
		}
		
		parent.put("children",children);
	}
	
	public List<Organization> children(){
		String id = getStr("id");
		return dao.find("select * from sys_organization where id like ? and LENGTH(id)=?",id+"%",id.length()+3);
	}
	
	public String nextId(){
		List<Organization> children = children();
		return getStr("id") + String.format("%03d",children.size());
	}
}
